import {
  getSettings,
  setSettings,
  loadSettingIntoDOM,
  applyTheme,
  populateLanguageSelect,
  t,
} from "./settings.js";
import { applyI18n } from "./i18n.js";
import { BasicCalculator } from "./widgets/basic.js";
import { ScientificCalculator } from "./widgets/scientific.js";
import { CurrencyConverter } from "./widgets/currency.js";
import { UnitConverter } from "./widgets/units.js";
import { CompoundCalculator } from "./widgets/compound.js";
import { DateCalculator } from "./widgets/dates.js";

function initTabs() {
  const tabs = Array.from(document.querySelectorAll(".tab"));
  const panes = Array.from(document.querySelectorAll(".pane"));
  tabs.forEach((tab) => {
    tab.addEventListener("click", () => {
      tabs.forEach((t) => t.classList.remove("is-active"));
      panes.forEach((p) => p.classList.remove("is-active"));
      tab.classList.add("is-active");
      const target = tab.dataset.tab;
      const pane = document.querySelector(`.pane[data-pane="${target}"]`);
      if (pane) pane.classList.add("is-active");
    });
  });
}

async function init() {
  const settings = await getSettings();
  applyTheme(settings.theme, settings.accentColor);
  await populateLanguageSelect(
    document.getElementById("languageSelect"),
    settings.language
  );
  await applyI18n(settings.language);
  document
    .getElementById("languageSelect")
    .addEventListener("change", async (e) => {
      const value = e.target.value;
      await setSettings({ language: value });
      location.reload();
    });

  document.getElementById("themeToggle").addEventListener("click", async () => {
    const next = document.documentElement.classList.contains("theme-light")
      ? "dark"
      : "light";
    applyTheme(next, settings.accentColor);
    await setSettings({ theme: next });
  });

  initTabs();

  new BasicCalculator(document.getElementById("basicCalculator"));
  new ScientificCalculator(document.getElementById("scientificCalculator"));
  new CurrencyConverter(document.getElementById("currencyConverter"));
  new UnitConverter(document.getElementById("unitConverter"));
  new CompoundCalculator(document.getElementById("compoundCalculator"));
  new DateCalculator(document.getElementById("dateCalculator"));
}

document.addEventListener("DOMContentLoaded", init);
